<template>
  <div class="app-container">
    <template v-if="!showDetailIndex">
      <div class="search-container">
        <el-form ref="form" :model="queryParams" :inline="true">
          <el-form-item prop="keywords" label="样本编号">
            <el-input v-model="queryParams.keywords" placeholder="样本编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <el-table v-loading="loading" :data="dataList" highlight-current-row border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" width="55" prop="dataIndex" />
          <el-table-column label="样本编号" prop="number" width="170"/>
          <el-table-column label="用户名" prop="userName" width="80"/>
          <el-table-column label="电话号" prop="phone" width="120"/>
          <el-table-column label="报告名称" prop="pdfName" />
          <el-table-column label="审核结论" prop="auditPassText" width="80"/>
          <el-table-column label="更新时间" prop="updateTimeText" width="180"/>
          <el-table-column fixed="right" label="操作" min-width="200" width="240">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="openReport(scope.row, 1)">预览</el-button>
              <el-button type="warning" size="small" v-if="scope.row.auditPass == null" link @click="openAuditDialog(scope.row, 0)">审核</el-button>
              <el-button type="info" size="small" v-if="scope.row.auditPass != null && !scope.row.auditPass" link @click="openAuditDialog(scope.row, 0)">重新审核</el-button>
              <el-button size="small" v-if="scope.row.auditPass == null" link @click="openEditDialog(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-card>

      <el-dialog :visible.sync="sampleReportDialog.visible" :title="sampleReportDialog.title" width="400px" :close-on-click-modal="false"
      :before-close="closeEditReportDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="所属应用" prop="dfApplicationId">
          <el-select v-model="formData.dfApplicationId" @change="changeApplication">
            <el-option v-for="field in applicationList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属关联模板" prop="reportTemplateId">
          <el-select v-model="formData.reportTemplateId">
            <el-option v-for="field in appTemplateList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-switch style="margin-left: 100px; margin-top: 18px;" v-model="geneCoverContent" active-text="封面加姓名" inactive-text="封面"></el-switch>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="geneSampleReport" :disabled="!formData.reportTemplateId">替换模板</el-button>
          <el-button @click="closeEditReportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    </template>

    <!-- 审核样本 -->
    <AuditSample :checkedSampleReport="checkedSampleReport" :valueId="valueId" v-if="showDetailIndex" @close="closeDetail">
    </AuditSample>
  </div>
</template>

<script>
import seqSampleApi from '@/api/sequence/seqSample'
import userApi from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import reportSampleApi from '@/api/report/reportSample';
import AuditSample from '@/views/audit/detail'

import seqSampleReportApi from '@/api/sequence/seqSampleReport';

import dfApplicationApi from '@/api/analysis/application';
import reportTemplateApi from '@/api/report/template'
import reportIndexApi from '@/api/report';
export default {
  name: 'labSampleIndex',
  components: {
    AuditSample
  },
  data() {
    return {
      queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
        statuses: ['REPORT_AUDIT', 'COMPLETED'],
        status: '',
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      userList: [],
      dialog: {},
      formData: {},
      rules: {},
      auditDialog: {},
      auditFormData: {},

      checkedRow: {},

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      auditPass: true,
      checkedSampleReport: {},
      htmlPdUrl: '',
      showDetailIndex: false,
      reportViewVisible: false,
      reportData: {},
      valueId: "",

      sampleReportDialog: {},
      applicationList: [],
      appTemplateList: [],
      geneCoverContent: false,
    };
  },
  mounted() {
  },
  methods: {
    geneSampleReport () {
      this.$confirm('此操作将覆盖已生成的样本报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '样本报告Pdf生成中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        seqSampleReportApi.parseReport(this.checkedRow.id).then(res1 => {
          if (res1.error) {
            this.$message({
              showClose: true,
              message: res1.data,
              type: 'error',
              duration: 0,
              customClass: 'messageErrorClass'
            });
            loading.close();
            return;
          }
          reportIndexApi.genePdf(this.formData.reportTemplateId, true, this.checkedRow.id, this.geneCoverContent).then((res) => {
            loading.close();
            let result = res;
            var binaryData = [];
            binaryData.push(result);
            let Blobs = new Blob(binaryData, { type: 'application/pdf' });
            this.htmlPdUrl = URL.createObjectURL(Blobs);
            this.$set(this.sampleReportDialog, 'visible', false);
            this.$message({ message: '报告模板替换成功，请点击【预览】查看生成内容！', type: 'success' });
          });
        })
      }).catch(() => {});
    },
    openEditDialog (row) {
      console.log(row)
      this.checkedRow = row;
      this.$set(this.sampleReportDialog, 'visible', true);
      this.$set(this.sampleReportDialog, 'title', '更换模板');
      dfApplicationApi.list().then(res => {
        this.applicationList = res.data;
        if (this.applicationList.length != 0) {
          reportTemplateApi.listByApplication(this.applicationList[0].id).then(r => {
            this.appTemplateList = r.data;
          })
        }
      })
    },
    closeEditReportDialog () {
      this.$set(this.sampleReportDialog, 'visible', false);
    },
    changeApplication (val) {
      this.appTemplateList = [];
      reportTemplateApi.listByApplication(val).then(r => {
        this.appTemplateList = r.data;
      })
    },
    // 公共loading
    customLoading() {
      var loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      return loading;
    },
    // 查看报告
    openReport(row, val) {
      // this.reportData = row;
      // this.reportViewVisible = true;
      // this.getReportData();
      this.checkedSampleReport = row;
      this.valueId = val
      this.showDetailIndex = true;
    },
    closeDetail() {
      this.showDetailIndex = false;
    },
    auditSample() {
      let auditPass = this.auditPass;
      reportSampleApi.auditSample({
        id: this.checkedSampleReport.id,
        auditPass: auditPass,
        auditResult: this.auditFormData.auditResult,
      }).then(res => {
        this.$message({ message: '样本审核完成！', type: 'success' });
        this.$set(this.auditDialog, 'visible', false);
        this.handleQuery();
      })
    },
    openAuditDialog(row, val) {
      this.checkedSampleReport = row;
      this.valueId = val
      this.showDetailIndex = true;
    },
    closeAuditDialog() {
      this.$set(this.auditDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        sampleType: 'REPORT',
        reportFile: true,
      };
      seqSampleReportApi.page(params).then((res) => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.dataIndex = index++;
          v.statusText = this.statusMap[v.sampleStatus]
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.auditPassText = v.auditPass == null ? '-' : (v.auditPass ? '通过' : '未通过')
        });
        this.dataList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
        statuses: ['REPORT_AUDIT', 'COMPLETED'],
        status: '',
      };
      this.handleQuery();
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    userApi.list().then((res) => {
      let data = res.data;
      this.userList = data;
    })
    this.handleQuery();
  }
};
</script>

<style>
.messageErrorClass .el-message__content  {
  max-height: 300px;
  overflow: auto;
}
</style>
<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}

.viewFileVisible_box {
  display: flex;
}

.input_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2% 1%;
  margin-right: 2%;
}

.input_file h3 {
  /* margin-bottom: 2%; */
}

.output_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2%;
}

.output_file h3 {
  /* margin-bottom: 2%; */
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}
</style>